//
//  SettingViewController.m
//  VICKY ZONE
//
//  Created by sunx on 15/3/24.
//  Copyright (c) 2015年 sunx. All rights reserved.
//
#define SERVER @"http://samoyun.com/controller/blogController.php"
#define MANAGER @"http://samoyun.com/controller/mainController.php"

#import "SettingViewController.h"
#import "HeadImageCell.h"
#import "ClearCell.h"
#import "BlogViewController.h"
#import "MyViewController.h"
#import "MoodCell.h"
#import "MainViewController.h"
#import "NSURLSession+KKAddition.h"
#import "GDataXMLNode.h"
#import "SVProgressHUD.h"
#import "UsernameCell.h"
#import "MenuButtonCell.h"

@interface MainViewController ()
@property(nonatomic,strong) NSString *username;
@property(nonatomic,strong) MoodCell *moodcell;
@property(nonatomic,strong) NSString *mood;
@property(nonatomic,strong) HeadImageCell *headcell;
@property(strong, nonatomic) UIImagePickerController *imagePicker;
@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //UIImage *background = [UIImage imageNamed:@"mainbac"];
    //self.view.backgroundColor =
    //self.tableView.backgroundColor =[UIColor colorWithPatternImage: [UIImage imageNamed:@"mainbac"] ];
    self.tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    self.tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    self.tableView.scrollEnabled = NO;
    self.view.backgroundColor = [UIColor grayColor];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mainbac"]];
    imageView.frame = self.view.frame;
    [self.view addSubview:imageView];
    [self.view sendSubviewToBack:imageView];
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    self.username = (NSString *)[userDefault objectForKey:@"username"];

    NSLog(@"%@",NSHomeDirectory());
    
    ClearCell *clear1 = [[ClearCell alloc] initWithHeight:0.06];

    //head cell
    NSString *head = [[NSString alloc] initWithFormat:@"http://samoyun.com/user/%@/imgs/_head.png",self.username];
    NSLog(@"%@",head);
    self.headcell = [[HeadImageCell alloc] initWithImageURL:head];
    self.headcell.actionBlock = ^{[self makeActionSheetAppear];};
    ClearCell *clear2 = [[ClearCell alloc] initWithHeight:0.02];

    UsernameCell *userNameCell = [[UsernameCell alloc] init];
    
    ClearCell *clear3 = [[ClearCell alloc] initWithHeight:0.06];
    
    //mood cell
    self.moodcell = [[MoodCell alloc] initWithString:@""];
    
    ClearCell *clear4 = [[ClearCell alloc] initWithHeight:0.02];

    
    MenuButtonCell *blogButtonCell = [MenuButtonCell buttonWithTitle:@"MY BLOG" andAction:^{
        BlogViewController *blog = [[BlogViewController alloc] init];
        [self.navigationController pushViewController:blog animated:YES];
    }];
    
    ClearCell *clear5 = [[ClearCell alloc] initWithHeight:0.015];

    
    MenuButtonCell *axisButtonCell = [MenuButtonCell buttonWithTitle:@"TIME AXIS" andAction:^{
        MyViewController *axis = [[MyViewController alloc] init];
        [self.navigationController pushViewController:axis animated:YES];
    }];
    
    ClearCell *clear6 = [[ClearCell alloc] initWithHeight:0.015];

    
    MenuButtonCell *settingButtonCell = [MenuButtonCell buttonWithTitle:@"SETTING" andAction:^{
        SettingViewController *setting = [[SettingViewController alloc] init];
        [self.navigationController pushViewController:setting animated:YES];
    }];
    /*
     //update mood button
    OrganicCell *updateButtonCell = [OrganicCell cellWithStyle:UITableViewCellStyleDefault height:70 actionBlock:^{
        [SVProgressHUD show];
        NSString *mood = self.moodcell.textView.text;
        if(![mood isEqualToString:self.mood]) {
            [NSURLSession POST:MANAGER pararms:@{@"user":self.username,@"mood":mood} completed:^(NSData *data) {
                [self performSelectorOnMainThread:@selector(HUDDissmiss) withObject:self waitUntilDone:YES];
                if(data == nil) {
                    NSLog(@"success");
                }else {
                    NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
                }
            } failed:^(NSError *error) {
                if(error) {
                    NSLog(@"%@",error);
                }
            }];
        }
    }];
    updateButtonCell.textLabel.text = @"MY HEART";
    updateButtonCell.textLabel.textAlignment = NSTextAlignmentCenter;
    updateButtonCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    
    //axis button
    OrganicCell *axisButtonCell = [OrganicCell cellWithStyle:UITableViewCellStyleDefault height:50 actionBlock:^{
        MyViewController *axis = [[MyViewController alloc] init];
        [self.navigationController pushViewController:axis animated:YES];
    }];
    axisButtonCell.textLabel.text = @"TIME AXIS";
    axisButtonCell.textLabel.textAlignment = NSTextAlignmentCenter;
    axisButtonCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    
    //settring button
    OrganicCell *setButtonCell = [OrganicCell cellWithStyle:UITableViewCellStyleDefault height:50 actionBlock:^{
        SettingViewController *setting = [[SettingViewController alloc] init];
        [self.navigationController pushViewController:setting animated:YES];
    }];
    setButtonCell.textLabel.text = @"SETTING";
    setButtonCell.textLabel.textAlignment = NSTextAlignmentCenter;
    setButtonCell.accessoryType  = UITableViewCellAccessoryDisclosureIndicator;
    */
    
    //OrganicSection *mainSection = [OrganicSection sectionWithCells:@[clearCell,self.headcell,self.moodcell,clearCell2]];
    
    
    
    OrganicSection *mainSection = [OrganicSection sectionWithCells:@[clear1,self.headcell,clear2,userNameCell,clear3,self.moodcell,clear4,blogButtonCell,clear5,axisButtonCell,clear6,settingButtonCell]];
    //OrganicSection *buttonSection = [OrganicSection sectionWithCells:@[updateButtonCell,clearCell,blogButtonCell,axisButtonCell,setButtonCell]];
    //self.sections = @[mainSection,buttonSection];
    self.sections = @[mainSection];
}

- (void)viewWillAppear:(BOOL)animated {
    //xml解析
    [NSURLSession GET:SERVER pararms:@{@"user":self.username,@"type":@"others"} completed:^(NSData *data) {
        
        GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil];
        GDataXMLElement *element = [document rootElement];
        self.mood = [[element children][2] stringValue];
        
        [self performSelectorOnMainThread:@selector(updateMood) withObject:nil waitUntilDone:YES];
        
    } failed:^(NSError *error) {
        if(error) {
            NSLog(@"%@",error);
        }
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Action Sheet
- (void)makeActionSheetAppear {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Change"
                                                             delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil
                                                    otherButtonTitles:@" Camera", @"Folder", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"actionSheet");
    // the user clicked one of the OK/Cancel buttons
    if (buttonIndex == 0) {
        [self pushTakePhotoScreenInDelegate];
    }
    else if (buttonIndex == 1) {
        [self pushChoosePhotoScreenInDelegate];
    }
}

-(void)pushTakePhotoScreenInDelegate
{
    self.imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePicker.delegate = self;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

-(void)pushChoosePhotoScreenInDelegate
{
    self.imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.imagePicker.delegate = self;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [SVProgressHUD show];
    self.headcell.imageView.image = image;
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    NSLog(@"%@",timeString);
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filename = @"_head.png";
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent: filename];
    [self removeImage];
    
    // 保存文件的名称
    BOOL result = [UIImagePNGRepresentation(self.headcell.imageView.image)writeToFile: filePath    atomically:YES];
    // 保存成功会返回YES
    if(result) {
        [NSURLSession Upload:filePath user:self.username type:@"header" filename:filename progress:^(CGFloat progress) {
            
        } completed:^(NSData *data){
            [self performSelectorOnMainThread:@selector(HUDDissmiss) withObject:self waitUntilDone:YES];
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        } failed:^(NSError *error) {
            if(error) {
                NSLog(@"%@",error);
            }
        }];
    }
}
#pragma mark - select motheds
- (void)HUDDissmiss {
    [SVProgressHUD dismiss];
}

- (void)updateMood {
    self.moodcell.textView.text = self.mood;
}

//上传头像之前删除之前的头像
- (void)removeImage {
    NSString *imageDir = [NSString stringWithFormat:@"%@/Documents/_head.png", NSHomeDirectory()];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:imageDir error:nil];
}
@end
